package com.df.blueben.aop;


import com.df.blueben.constant.JwtClaimsConstant;
import com.df.blueben.context.BaseContext;
import com.df.blueben.exception.BusinessException;
import com.df.blueben.exception.ErrorCode;
import com.df.blueben.properties.JwtProperties;
import com.df.blueben.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Aspect
@Component
@Slf4j
public class verifyLoginAop {

    @Autowired
    JwtProperties jwtProperties;

    /**
     * 打了NeedLogin注解的方法都会被拦截
     */
    @Before("@annotation(com.df.blueben.annotations.NeedLogin)")
    public void verifyLogin(){
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes())
                .getRequest();

        String token = request.getHeader("token");
        if(token == null){
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR,"用户未登录");
        }
        //解析用户信息获得用户id
        //2、校验令牌
        try {
            log.info("jwt校验:{}", token);
            Claims claims = JwtUtil.parseJWT(jwtProperties.getUserSecretKey(), token);
            Long userId = Long.valueOf(claims.get(JwtClaimsConstant.USER_ID).toString());
            //将empID存入ThreadLocal中
            BaseContext.setCurrentId(userId);
            log.info("当前用户id：{}", userId);
        }catch (Exception e){
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR,"用户未登录");
        }
    }
}
